package com.adtech.core.dao;

import org.hibernate.EmptyInterceptor;

/**
 * 空值排序拦截器
 * 解决空值排序
 * @author Dormin
 * @since 2012-12-12
 *
 * @Copyright (C) AD Tech Workshop All Right Reserved
 */
public class NullOrderIInterceptor extends EmptyInterceptor {
    private static final String ORDER_BY_TOKEN = "order by";

    public String onPrepareStatement(String sql) {

        int orderByStart = sql.toLowerCase().indexOf(ORDER_BY_TOKEN);
        if (orderByStart == -1) {
            return super.onPrepareStatement(sql);
        }
        orderByStart += ORDER_BY_TOKEN.length() + 1;
        int orderByEnd = sql.indexOf(")", orderByStart);
        if (orderByEnd == -1) {
            orderByEnd = sql.indexOf(" UNION ", orderByStart);
            if (orderByEnd == -1) {
                orderByEnd = sql.length();
            }
        }
        String orderByContent = sql.substring(orderByStart, orderByEnd);
        String[] orderByNames = orderByContent.split("\\,");
//        for (int i=0; i<orderByNames.length; i++) {
//            if (orderByNames[i].trim().length() > 0) {
//                if (orderByNames[i].trim().toLowerCase().endsWith("desc")) {
//                    orderByNames[i] += " NULLS LAST";
//                } else {
//                    orderByNames[i] += " NULLS FIRST";
//                }
//            }
//        }
        //orderByContent = StringUtils.join(orderByNames, ",");
        StringBuilder buffer = new StringBuilder();
        for(String order : orderByNames) {
            if(order!=null && order.length()>0) {
                buffer.append(order).append(",");
            }
        }
        orderByContent = buffer.toString();
        if(orderByContent.length()>0) {
            orderByContent = orderByContent.substring(0,orderByContent.length()-1);
        }
        sql = sql.substring(0, orderByStart) + orderByContent + sql.substring(orderByEnd);
        return super.onPrepareStatement(sql);
    }
}
